package com.anxin.act.task.cmd;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;

import java.util.List;

/**
 * @author: liuxiangyu
 * @date: 2020/8/10 14:13
 */
public class UpdateNrOfInstancesCmd implements Command<Void> {

    private String taskId;


    public UpdateNrOfInstancesCmd(String taskId) {
        this.taskId = taskId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        TaskEntity taskEntity = Context.getCommandContext().getTaskEntityManager().findTaskById(taskId);
        ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();
        ExecutionEntity execution = executionEntityManager.findExecutionById(taskEntity.getExecutionId());
        ExecutionEntity parent = execution.getParent();

        if (parent != null){
            ExecutionEntity parentParent = executionEntityManager.findExecutionById(parent.getParentId());

            if (parentParent == null){
                return null ;
            }

            List<ExecutionEntity> executions = parent.getExecutions();
            Integer taskNum = getRuTaskNum(parent,executionEntityManager);


            int executionNum = 0;
            List<ExecutionEntity> childExecutionsByParentExecutionList = executionEntityManager.findChildExecutionsByParentExecutionId(parent.getId());
            for (ExecutionEntity executionEntity : childExecutionsByParentExecutionList) {
                if (executionEntity.isActive()){
                    executionNum ++;
                }
            }


            if (taskNum == 1 && executionNum== 1){
                parent.setVariableLocal("nrOfInstances",taskNum);
                parent.setVariableLocal("nrOfActiveInstances",taskNum);
            }
        }
        //Context.getCommandContext().getTaskEntityManager().de
        return null;
    }


    public int getRuTaskNum(ExecutionEntity parent,ExecutionEntityManager executionEntityManager) {

        int taskNum = 0;
        List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(parent.getId());
        for (ExecutionEntity executionEntity : executions) {
            List<TaskEntity> tasks = executionEntity.getTasks();
            for (TaskEntity task : tasks) {
                taskNum ++;
            }
            taskNum += getRuTaskNum(executionEntity,executionEntityManager);
        }
        return taskNum;
    }
}
